package loadBalancer;

import cn.hutool.core.collection.CollUtil;
import model.ServiceInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡器
 */
public class RoundBalancer implements LoadBalance {
    /**
     * 原子计数器，避免并发安全
     */
    private static final AtomicInteger index = new AtomicInteger(0);
    public ServiceInfo selectServiceFromList(Map<String,Object> requestParams, List<ServiceInfo> serviceInfoList){
        //为空则返回null，说明没有可用服务
        if(CollUtil.isEmpty(serviceInfoList))return null;
        //若只有一个服务，直接取第一个
        int size = serviceInfoList.size();
        if(size == 1)return serviceInfoList.get(0);
        //有多个，按照轮询来
        ServiceInfo selectedServiceInfo = serviceInfoList.get(index.getAndIncrement() % size);
        return selectedServiceInfo;
    }
}
